import {
    View,
    Text,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    Image,
    ScrollView,
    KeyboardAvoidingView
} from 'react-native'
import React, {Component} from 'react'
import {border, padding, default as styles, HUNDRED_PERCENT} from "../../style";
import LabelCellWithRightComp from "../../component/widget/labelCellWithRightComp";
import {Actions} from "react-native-router-flux";
import toast from "../../component/common/ToastProxy";
import {defaultObj, getAssetUrl, isPhoneAvailable, validObjHasEmpty} from "../../util";
import {Store} from "../../store";
import {inject, observer} from "mobx-react/custom";
import {showImagePicker} from "../../component/common/ImagePickerProxy";
import FastImageCustom from "../../component/widget/FastImageCustom";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import {uploadFile} from "../../net";
import {BaseTimer, DEFAULT_VERIFICATION_TIME_OUT} from "../../util/timer";

interface VerifiedProps extends Store {

}

interface VerifiedState {
    realName: string;
    phone: string;
    verifiedCode: string;
    idNumber: string;
    timerCountDown: number;

    idNegative?: string;
    idPositive?: string;
    bankAccount?: string;
    bankAddress?: string;
    bankAccountHolder?: string;

}

@inject("verified")
@observer
export default class Verified extends Component<VerifiedProps, VerifiedState> {

    timer: BaseTimer = null;


    constructor(props: VerifiedProps) {
        super(props);
        this.state = {
            ...defaultObj,
            timerCountDown: 0
        };
    }

    componentWillUnmount() {
        this.timer && this.timer.clearTimer();
    }

    _renderTips() {
        return (<View style={[padding(10, 20), {backgroundColor: "#FFFCE1"}]}>
            <Text numberOfLines={0} style={VerifiedStyle.tipFont}>实名认证成功可提现(一周可提现一次)</Text>
        </View>);
    }

    timerCallBack = (timer: BaseTimer) => {
        this.setState({
            timerCountDown: timer.count
        })
    };
    validPhoneNumber = async () => {
        if (this.state.phone != null && isPhoneAvailable(this.state.phone)) {
            global.showLoading();
            const code = await this.props.verified.validUserPhone(this.state.phone);
            if (code === 200) {
                global.showSuccess("发送成功!");
                this.timer = new BaseTimer(DEFAULT_VERIFICATION_TIME_OUT, this.timerCallBack, 1000)
            } else {
                global.showError("发送失败,请不要在短时间内连续发送验证码!")
            }
        } else {
            global.showError("格式错误!")
        }
    };

    _renderPhoneVerifiedCmp() {
        const disabled = this.state.timerCountDown !== 0;
        const backgroundColor = disabled ? "#ccc" : null;
        const borderColor = disabled ? "#ccc" : "#629B36";
        const textColor = disabled ? "#fff" : "#629B36";
        return (<View style={[styles.centerH, styles.flexDirectionRow]}>
            <TextInput autoCorrect={true} autoCapitalize={"none"} underlineColorAndroid={"transparent"}
                       onChangeText={this.updateInputValue("phone")}
                       keyboardType={"number-pad"}
                       style={VerifiedStyle.inputStyle} placeholder={"请输入手机号码"}/>
            <TouchableOpacity onPress={this.validPhoneNumber}
                              disabled={disabled}
                              style={[padding(7, 15), border(1, borderColor), {
                                  borderRadius: 15,
                                  marginLeft: 10,
                                  backgroundColor
                              }]}>
                <Text style={{
                    fontSize: 12,
                    color: textColor,
                    fontWeight: "bold"
                }}>{!disabled ? '获取验证码' : `${this.state.timerCountDown}秒后重新发送`}</Text>
            </TouchableOpacity>
        </View>)
    }

    updateInputValue(key: string) {
        return (inputVal: string) => {
            const state: any = {
                [key]: inputVal
            };
            this.setState(state);
        }
    }

    uploadForm = async () => {
        if (this.props.verified.verificationCode === this.state.verifiedCode) {
            global.showLoading();
            const form = {
                realName: this.state.realName,
                phone: this.state.phone,
                idNumber: this.state.idNumber,
                idNegative: this.state.idNegative,
                idPositive: this.state.idPositive,
                bankAccount: this.state.bankAccount,
                bankAccountHolder: this.state.bankAccountHolder,
                bankAddress: this.state.bankAddress,
            };
            if (validObjHasEmpty(form)) {
                return global.showError("请检查表单是否填写完整");
            }
            await this.props.verified.insertUserRealInfo(form);
            global.showSuccess("上传成功", 500, () => {
                Actions.push("VerifiedResult");
            });
        } else {
            toast("验证码错误!");
        }

    };

    _renderInputs() {
        return (<View>
            <LabelCellWithRightComp label={{text: "真实姓名", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput onChangeText={this.updateInputValue("realName")}
                                                         autoCorrect={true}
                                                         autoCapitalize={"none"}
                                                         underlineColorAndroid={"transparent"}
                                                         style={VerifiedStyle.inputStyle} placeholder={"请输入真实姓名"}/>}/>

            <LabelCellWithRightComp label={{text: "手机号码", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={this._renderPhoneVerifiedCmp()} style={padding(10, 20)}/>

            <LabelCellWithRightComp label={{text: "验证码", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput autoCorrect={true} autoCapitalize={"none"}
                                                         underlineColorAndroid={"transparent"}
                                                         keyboardType={"number-pad"}
                                                         onChangeText={this.updateInputValue("verifiedCode")}
                                                         style={VerifiedStyle.inputStyle} placeholder={"请输入验证码"}/>}/>

            <LabelCellWithRightComp label={{text: "身份证号", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput autoCorrect={true} autoCapitalize={"none"}
                                                         onChangeText={this.updateInputValue("idNumber")}
                                                         underlineColorAndroid={"transparent"}
                                                         keyboardType={"number-pad"}
                                                         style={VerifiedStyle.inputStyle} placeholder={"请输入身份证号码"}/>}/>
            <LabelCellWithRightComp label={{text: "持卡人", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput autoCorrect={true} autoCapitalize={"none"}
                                                         onChangeText={this.updateInputValue("bankAccountHolder")}
                                                         underlineColorAndroid={"transparent"}
                                                         style={VerifiedStyle.inputStyle} placeholder={"张三"}/>}/>
            <LabelCellWithRightComp label={{text: "开户行地址", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput autoCorrect={true} autoCapitalize={"none"}
                                                         onChangeText={this.updateInputValue("bankAddress")}
                                                         underlineColorAndroid={"transparent"}
                                                         style={VerifiedStyle.inputStyle}
                                                         placeholder={"中国建设银行江苏省分行"}/>}/>
            <LabelCellWithRightComp label={{text: "银行卡号", textStyle: VerifiedStyle.inputLabelStyle}}
                                    rightCmp={<TextInput autoCorrect={true} autoCapitalize={"none"}
                                                         keyboardType={"number-pad"}
                                                         onChangeText={this.updateInputValue("bankAccount")}
                                                         underlineColorAndroid={"transparent"}
                                                         style={VerifiedStyle.inputStyle}
                                                         placeholder={"62284 80010 200900 214"}/>}/>
        </View>)
    }

    uploadIDImage(key: string) {
        return async () => {
            const res = await showImagePicker(), {uri, fileName="defalut.JPG"} = res;
            console.log(res);
            // const local = this.state.local || defaultObj;
            global.showLoading();
            try {
                const file = await uploadFile(uri, fileName);
                const state: any = {
                    [key]: file
                };
                this.setState(state);
                global.showSuccess("上传成功!");
            } catch (e) {
                global.showError("上传失败,请联系开发人员!")
            }
        };
    }


    _renderIDUpload() {
        const idPositivePlaceHolder = require("../../assets/img/id_fan.png");
        const idNegativePlaceHolder = require("../../assets/img/id_zheng.png");
        // const localImage = this.state.local || defaultObj;
        return (
            <View style={[{marginTop: 8, backgroundColor: "#fff"}, padding(16, 18)]}>
                <Text style={{marginBottom: 8, fontSize: 14, color: "#333"}}>上传身份证</Text>
                <View style={[styles.flexDirectionRowNotFlex, styles.justifyBetween]}>
                    <TouchableOpacity onPress={this.uploadIDImage("idNegative")} style={[{
                        backgroundColor: "#F3F3F3",
                        paddingBottom: 25,
                        width: 166,
                        height: 100
                    }, styles.centered]}>
                        {this.state.idNegative ?
                            <FastImageCustom style={{width: HUNDRED_PERCENT, height: HUNDRED_PERCENT}}
                                             resizeMode={"cover"}
                                             source={{uri: getAssetUrl(this.state.idNegative)}}/>
                            : <Image source={idNegativePlaceHolder} style={{width: 70, height: 46}}/>
                        }
                        <View style={[styles.absoluteFull, styles.centered, {
                            backgroundColor: "#484848",
                            top: null,
                            height: 25
                        }]}>
                            <Text style={{fontSize: 12, color: "#fff"}}>上传身份证正面</Text>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={this.uploadIDImage("idPositive")} style={[{
                        backgroundColor: "#F3F3F3",
                        paddingBottom: 25,
                        width: 166,
                        height: 100
                    }, styles.centered]}>
                        {this.state.idPositive ?
                            <FastImageCustom style={{width: HUNDRED_PERCENT, height: HUNDRED_PERCENT}}
                                             resizeMode={"cover"}
                                             source={{uri: getAssetUrl(this.state.idPositive)}}/>
                            : <Image source={idPositivePlaceHolder} style={{width: 70, height: 46}}/>
                        }
                        <View style={[styles.absoluteFull, styles.centered, {
                            backgroundColor: "#484848",
                            top: null,
                            height: 25
                        }]}>
                            <Text style={{fontSize: 12, color: "#fff"}}>上传身份证反面</Text>
                        </View>
                    </TouchableOpacity>

                </View>
            </View>
        )
    }

    render() {
        return (<KeyboardAwareScrollView style={VerifiedStyle.container}>
            {this._renderTips()}
            {this._renderInputs()}
            {this._renderIDUpload()}
            <TouchableOpacity
                onPress={this.uploadForm}
                style={[styles.centered, {
                    marginHorizontal: 14,
                    paddingVertical: 12,
                    backgroundColor: "#629C36",
                    borderRadius: 30,
                    marginTop: 20
                }]}>
                <Text style={VerifiedStyle.btnFont}>提现</Text>
            </TouchableOpacity>
        </KeyboardAwareScrollView>)
    }
}

const VerifiedStyle = StyleSheet.create({
    container: {},
    tipFont: {
        color: "#FF7408",
        fontSize: 14
    },
    inputLabelStyle: {
        width: 100
    },
    inputStyle: {
        textAlign: "left",
        flex: 1,
        paddingTop: 0,
        paddingBottom: 0,
        paddingLeft: 0,
        paddingRight: 0,
    }, btnFont: {
        fontSize: 14,
        color: "#fff"
    }
});

 